package com.huaxindata.im.main.chat.mp3recorder.netnat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import static com.huaxindata.im.main.chat.mp3recorder.netnat.NetNatConfig.BUFFSERSIZE;
import static com.huaxindata.im.main.chat.mp3recorder.netnat.NetNatConfig.C_PORT;

public class NetNatHelper implements Runnable {


    private static NetNatHelper instance;

    NetNatSender natSender;

    private NetNatHelper() {
    }

    public synchronized static NetNatHelper getInstance() {
        if (instance == null) {
            instance = new NetNatHelper();
        }
        return instance;
    }

    public void init() {
        try {
            if (socket == null) {
                socket = new DatagramSocket(C_PORT);
                natSender = new NetNatSender(socket);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void stopListener() {
        running = false;
        if (socket != null) {
            socket.close();
            socket = null;
        }
        if (natSender != null) {
            natSender.stopSender();
            natSender = null;
        }
    }

    public void startListener() {
        if (socket == null || natSender == null) {
            throw new RuntimeException("Must Call init before!");
        }
        if (running) {
            return;
        }
        running = true;
        natSender.startSender();
        new Thread(this).start();
    }

    boolean running = false;
    DatagramSocket socket;

    @Override
    public void run() {
        byte[] buffer = new byte[BUFFSERSIZE];
        DatagramPacket receive = new DatagramPacket(buffer, BUFFSERSIZE); // 发送的数据包
        while (!Thread.interrupted() && running) {
            try {
                socket.receive(receive);
                natSender.addPacket(receive.getAddress(), receive.getData(), receive.getLength());
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
